#!/bin/bash

# 重新编译和部署脚本
# 使用方法：在 Jenkins 服务器 (172.16.2.23) 上执行此脚本

set -e

echo "======================================"
echo "🔨 开始重新编译 jar-monitor"
echo "======================================"

# 1. 停止当前运行的服务
echo "⏸️  停止当前服务..."
PID=$(ps -ef | grep jar-monitor.jar | grep -v grep | awk '{print $2}')
if [ -n "$PID" ]; then
    kill $PID
    echo "✅ 已停止进程 PID: $PID"
    sleep 3
else
    echo "ℹ️  没有运行中的服务"
fi

# 2. 清理和编译
echo ""
echo "🧹 清理旧文件..."
mvn clean

echo ""
echo "📦 开始编译打包..."
mvn package -DskipTests

# 3. 检查编译结果
if [ ! -f "target/jar-monitor.jar" ]; then
    echo "❌ 编译失败！jar 文件不存在"
    exit 1
fi

echo ""
echo "✅ 编译成功！"
ls -lh target/jar-monitor.jar

# 4. 启动新服务
echo ""
echo "🚀 启动新服务..."
nohup java -Dserver.port=8000 -jar target/jar-monitor.jar > app.log 2>&1 &
NEW_PID=$!

echo "✅ 服务已启动，PID: $NEW_PID"

# 5. 等待服务启动
echo ""
echo "⏳ 等待服务启动..."
sleep 10

# 6. 健康检查
echo ""
echo "🏥 执行健康检查..."
HEALTH_CHECK=$(curl -s http://localhost:8000/actuator/health | grep -o '"status":"UP"' || echo "")

if [ -n "$HEALTH_CHECK" ]; then
    echo "✅ 服务健康检查通过！"
    echo ""
    echo "======================================"
    echo "🎉 部署成功！"
    echo "======================================"
    echo "📍 Web 控制台: http://172.16.2.23:8000"
    echo "📍 健康检查: http://172.16.2.23:8000/actuator/health"
    echo "📍 Prometheus: http://172.16.2.23:8000/actuator/prometheus"
    echo "📍 API 状态: http://172.16.2.23:8000/api/simulator/status"
    echo "======================================"
else
    echo "❌ 健康检查失败，请查看日志："
    echo "tail -f app.log"
    exit 1
fi
